using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace RegexEditor
{
	public class TextBoxState : IDisposable
	{
		#region Constants

		private const int SB_HORZ = 0x0;
		private const int SB_VERT = 0x1;

		#endregion

		#region Private Fields

		private static TextBoxState _current = null;
		private TextBoxBase _textBox;
		private int _scrollHPosition;
		private int _scrollVPosition;
		private bool _enabled;
		private PaintLock _paintLock;

		#endregion

		#region Constructors

		public TextBoxState(TextBoxBase textBox)
		{
			_enabled = _current == null;

			if (_enabled)
			{
				_paintLock = new PaintLock(textBox);

				_scrollHPosition = GetScrollPos(textBox.Handle, SB_HORZ);
				_scrollVPosition = GetScrollPos(textBox.Handle, SB_VERT);
				Start = textBox.SelectionStart;
				Length = textBox.SelectionLength;
				_textBox = textBox;
				_current = this;
			}
		}

		#endregion

		#region Public Members

		public int Start { get; set; }
		public int Length { get; set; }

		public void Dispose()
		{
			if (_enabled)
			{
				_textBox.SelectionStart = Start;
				_textBox.SelectionLength = Length;
				SetScrollPos(_textBox.Handle, SB_HORZ, _scrollHPosition, false);
				SetScrollPos(_textBox.Handle, SB_VERT, _scrollVPosition, false);
				_paintLock.Dispose();
				_current = null;
			}
		}

		#endregion

		#region Private Members

		[DllImport("user32.dll", CharSet = CharSet.Auto)]
		private static extern int GetScrollPos(IntPtr hWnd, int nBar);

		[DllImport("user32.dll")]
		static extern int SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw);

		#endregion
	}
}
